import React, { useEffect, useState, useCallback, useMemo } from 'react';
import {
  Table,
  Form,
  Input,
  Button,
  Modal,
  Col,
  Checkbox,
  DatePicker,
  Select,
} from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import type { ColumnsType } from 'antd/es/table';
import { DataType, getDishByIdAPI } from '@/service/dish';
import { GetSeatById, getSeatByIdAPI, Seat } from '@/service/seat';
import { OrderData, saveOrderAPI } from '@/service/order';
import { getMyCouponAPI } from '@/service/coupon';

const { Search } = Input;
dayjs.extend(customParseFormat);

const App: React.FC = () => {
  const restaurantId = localStorage.getItem('restaurant');
  const discount = localStorage.discount;
  const [order, setOrder] = useState(
    JSON.parse(localStorage.getItem('restaurantId' + restaurantId) || '{}'),
  );
  const [data, setData] = useState<DataType[]>();

  const [loading, setLoading] = useState(false);
  const [money, setMoney] = useState(0); // 将 money 设置为状态变量

  function updateOrder(id: number, change: number, number?: number) {
    let newOrder = { ...order }; // 创建一个新的订单对象
    let count = (order[id] || 0) + change;
    if (number !== undefined && count > number) {
      Modal.info({
        title: '提示',
        content: '库存不足',
      });
      return;
    }

    if (count <= 0) {
      //弹出确认框
      Modal.confirm({
        title: '提示',
        content: '是否删除该菜品',
        onOk() {
          delete newOrder[id];
          localStorage.setItem(
            'restaurantId' + restaurantId,
            JSON.stringify(newOrder),
          );
          fetchData();
        },
      });
    } else {
      newOrder[id] = count;
    }

    localStorage.setItem(
      'restaurantId' + restaurantId,
      JSON.stringify(newOrder),
    );
    setOrder(newOrder); // 更新状态，重新渲染组件
    debugger;
    setMoney(
      Number(
        (
          (data || [])
            .map((item) => item.price * ((order && order[item.id]) || 0))
            .reduce((a, b) => a + b, 0) * discount
        ).toFixed(2),
      ),
    );
    return order;
  }

  useEffect(() => {
    localStorage.setItem('restaurantId' + restaurantId, JSON.stringify(order));
    setMoney(
      Number(
        (
          (data || [])
            .map((item) => item.price * ((order && order[item.id]) || 0))
            .reduce((a, b) => a + b, 0) * discount
        ).toFixed(2),
      ),
    );
  }, [order]);

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '图片',
        dataIndex: 'image',
        render: (image) => (
          <img
            src={`http://localhost:10001/ftp/download?fileName=${image}&path=dish`}
            alt=""
            width="100"
            height="100"
          />
        ),
        width: '10%',
      },
      {
        title: '菜名',
        dataIndex: 'name',
        sorter: true,
        render: (name) => `${name}`,
        width: '15%',
      },
      {
        title: '分类',
        dataIndex: 'classify',
        filters: [
          { text: '未分类', value: '1' },
          { text: '热菜', value: '2' },
          { text: '凉菜', value: '3' },
          { text: '主食', value: '4' },
          { text: '汤类', value: '5' },
          { text: '饮品', value: '6' },
          { text: '甜品', value: '7' },
          { text: '其他', value: '8' },
        ],
        render: (classify) => `${classify}`,
        width: '10%',
      },
      {
        title: '库存',
        dataIndex: 'number',
        sorter: true,

        render: (number) => `${number} 份`,
        width: '10%',
      },
      {
        title: '评分',
        dataIndex: 'score',
        sorter: true,
        render: (score) => `${score} 分`,
        width: '10%',
      },
      {
        title: '销量',
        dataIndex: 'sales',
        sorter: true,
        render: (sales) => `${sales} 分`,
        width: '10%',
      },
      {
        title: '价格',
        dataIndex: 'price',
        sorter: true,
        render: (price) => `￥${price}元`,
        width: '10%',
      },
      {
        title: '下单',
        dataIndex: 'id',
        render: (id, record) => (
          <div>
            <Button
              onClick={() => {
                updateOrder(id, 1, record.number);
              }}
            >
              +
            </Button>
            {order[id] || 0}
            <Button
              onClick={() => {
                updateOrder(id, -1);
              }}
            >
              -
            </Button>
          </div>
        ),
        width: '10%',
      },
    ],
    [order],
  );
  const dateFormat = 'YYYY-MM-DD';

  let orderTime = dayjs().add(1, 'day').format(dateFormat);

  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);
    let orders = JSON.parse(
      localStorage.getItem('restaurantId' + restaurantId) || '{}',
    );

    const key = Object.keys(orders).map(Number);
    const value = Object.values(orders);
    try {
      const res = await getDishByIdAPI(key);
      if (res === undefined) return;
      res.forEach((item: any, index: any) => {
        item.count = value[index];
      });
      setData(res);
    } finally {
      setLoading(false);
    }
    console.log(data);
  }, []);
  //获取明天日期
  const minDate = dayjs().add(1, 'day').format(dateFormat);
  const maxDate = dayjs().add(1, 'week').format(dateFormat);
  const [coupons, setCoupons] = useState([]);
  useEffect(() => {
    const fetchCoupons = async () => {
      const res = await getMyCouponAPI(7);
      setCoupons(res);
    };
    fetchCoupons();
  }, []);

  const getSeatTime = async (data: any) => {
    orderTime = dayjs(data).add(1, 'day').format('YYYY-MM-DD');
    const getSeatById: GetSeatById = {
      time: orderTime,
      restaurantId: Number(localStorage.getItem('restaurant')),
    };
    const res = await getSeatByIdAPI(getSeatById);
    return res;
  };
  const times = {
    1: '上午',
    2: '中午',
    3: '下午',
    4: '晚上',
  };

  let seatId = 0;
  let seatName = '';
  let timeName = '';
  let timeNumber = 0;
  let userDist = 0;
  let couponId = 0;

  const getTimes = (time: number, item: any) => {
    timeNumber = time;
    timeName = JSON.stringify(times[time]);
    seatName = item.seatName;
    seatId = Number(JSON.stringify(item.id));
  };
  const getSeat = async () => {
    const getSeatById: GetSeatById = {
      time: orderTime,
      restaurantId: Number(localStorage.getItem('restaurant')),
    };
    const res = await getSeatByIdAPI(getSeatById);
    if (res === undefined) return;
    Modal.confirm({
      title: '选座',
      content: (
        <div>
          <Select
            placeholder="选择优惠券"
            onChange={(value) => {
              const selectedCoupon = coupons.find(
                (coupon) => coupon.id === value,
              );
              if (selectedCoupon) {
                userDist = selectedCoupon.discount;
                couponId = selectedCoupon.id;
              }
            }}
          >
            {coupons.map((coupon) => (
              <Option key={coupon.id} value={coupon.id}>
                {coupon.title + '---' + coupon.discount * 100 + '折'}
              </Option>
            ))}
          </Select>
          <DatePicker
            defaultValue={dayjs(minDate, dateFormat)}
            minDate={dayjs(minDate, dateFormat)}
            maxDate={dayjs(maxDate, dateFormat)}
            onChange={(data) => getSeatTime(data)}
          />
          <table>
            <tr>
              <th>座位名</th>
              <th>座位大小</th>
              <th>可预约时间段</th>
            </tr>
            {res.map((item: Seat, index: number) => {
              return (
                <tr key={index}>
                  <td>{item.seatName}</td>
                  <td>{item.seatSize}</td>
                  <td>
                    {item.time.map((time) => {
                      return (
                        <Checkbox
                          key={time}
                          onClick={() => getTimes(time, item)}
                        >
                          {times[time]}
                        </Checkbox>
                      );
                    })}
                  </td>
                </tr>
              );
            })}
          </table>
        </div>
      ),
      width: 500, // 设置Modal的宽度
      onOk() {
        Modal.confirm({
          title: '确认订单',
          content: (
            <div>
              <p>
                预约时间：
                {orderTime}:{timeName}
              </p>
              <p>
                座位：
                {seatName}
              </p>
              <p>
                菜品：
                {data
                  ?.map((item) => item.name + 'x' + order[item.id])
                  .join('、')}
              </p>
              <p>
                总金额：￥
                {(money * userDist).toFixed(2)}元{' '}
              </p>
            </div>
          ),
          async onOk() {
            const orderData: OrderData = {
              couponId: couponId,
              userDist: userDist,
              userId: localStorage.id,
              orderDetail: JSON.stringify(order),
              seatId: seatId,
              orderMoney: (money * userDist).toFixed(2),
              datePeriod: orderTime,
              timePeriod: timeNumber,
              userRemarks: '',
              paymentManner: '',
              paymentTime: '',
              restaurantId: Number(restaurantId),
            };

            await saveOrderAPI(orderData);
            Modal.info({
              title: '提示',
              content: '预约成功',
            });
            localStorage.removeItem('restaurantId' + restaurantId);
            window.location.href = 'http://localhost:8000/userOrder';
          },
        });
      },
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      <Form>
        <Search
          placeholder="菜品名称"
          allowClear
          enterButton="Search"
          size="small"
          maxLength={10}
        />
      </Form>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        scroll={{ y: 530 }}
      />
      总金额：￥
      {(
        (data || [])
          .map((item) => item.price * ((order && order[item.id]) || 0))
          .reduce((a, b) => a + b, 0) * discount
      ).toFixed(2)}
      元<Button onClick={getSeat}>选座</Button>
      当前会员折扣：{discount * 100}折
    </div>
  );
};

export default App;
